<template>
  <page-container :title="false" :breadcrumb="false">
    <div class="box-container">
      <a-form-model layout="inline" :model="queryParams">
        <a-form-model-item label="菜单名称">
          <a-input v-model="queryParams.name" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="菜单状态">
          <a-select v-model="queryParams.isShow" allow-clear style="width: 160px">
            <a-select-option v-for="item in viewTypeDict" :key="item.id" :value="item.dictValue" allow-clear>
              {{ item.dictLabel }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button
            icon="search"
            html-type="submit"
            @click="getTableDataByFirst"
          >
            查询
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="mt10">
      <div class="table_title_operate">
        <div class="left">
          <a-button
            type="primary"
            plain
            @click="onOpenAddMenuModal"
          >新增菜单</a-button>
        </div>
      </div>

      <s-table
        ref="table"
        class="bg-white"
        row-key="id"
        :columns="tableParams.columns"
        :data="tableParams.loadData"
        :init-request="tableParams.initRequest"
        :show-pagination="false"
      >
        <span slot="isShow" slot-scope="text">
          <a-badge v-if="text === 'SHOW'" status="success" text="显示" />
          <a-badge v-else status="error" text="隐藏" />
        </span>
        <span slot="operate" slot-scope="text, record, index">
          <template>
            <a @click="onOpenModifyMenuModal(index, record)">修改</a>
            <a-divider type="vertical" />
            <a @click="onDeleteMenu(index, record)">删除</a>
          </template>
        </span>
      </s-table>
    </div>

    <a-modal v-model="open" :title="title">
      <a-form-model ref="menuForm" :model="menuForm" :rules="menuFormRules">
        <a-row>
          <a-col :span="24">
            <a-form-item prop="parentId" label="上级菜单" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <treeselect v-model="menuForm.parentId" :normalizer="normalizer" placeholder="请选择上级菜单" :options="menuTree" :show-count="true" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item prop="menuType" label="菜单类型" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <a-radio-group v-model="menuForm.menuType">
                <a-radio v-for="item in menuTypeDict" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="name" label="菜单名称" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="treeSort" label="显示排序" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input-number v-model="menuForm.treeSort" style="width: 100%" :min="0" />
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType != 'BUTTON'" :span="12">
            <a-form-item prop="menuUrl" label="路由地址" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.menuUrl" />
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType == 'MENU'" :span="12">
            <a-form-item prop="componentPath" label="组件地址" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.componentPath" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="menuWeb" label="权限标识" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.menuWeb" />
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType != 'BUTTON'" :span="12">
            <a-form-item prop="isShow" label="显示状态" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-radio-group v-model="menuForm.isShow">
                <a-radio v-for="item in viewTypeDict" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType == 'MENU'" :span="12">
            <a-form-item label="是否缓存" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-radio-group v-model="menuForm.keepAlive">
                <a-radio v-for="item in yesNoDict" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType != 'DIRECTORY'" :span="12">
            <a-form-item label="菜单图标" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.menuIcon" />
            </a-form-item>
          </a-col>
          <a-col v-if="menuForm.menuType == 'DIRECTORY'" :span="12">
            <a-form-item label="重定向地址" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.redirect" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="后台地址" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="menuForm.menuHref" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="请求方式" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-select v-model="menuForm.method">
                <a-select-option v-for="item in requestTypeDict" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form-model>

      <template slot="footer">
        <a-button key="back" @click="open = false">
          取消
        </a-button>

        <template v-if="!menuForm.id">
          <!--新增-->
          <a-button key="submit" type="primary" @click="onAddOrModifyMenu">确认</a-button>
        </template>
        <template v-else>
          <!--修改-->
          <a-button key="submit" type="primary" @click="onAddOrModifyMenu">确认</a-button>
        </template>

      </template>
    </a-modal>
  </page-container>
</template>

<script>
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { debounce, deleteNullChildren, parseTime } from '@/utils'

import { addMenuApi, modifyMenuApi, deleteMenuApi, getMenuTreeApi } from '@/api/system/menu'

export default {
  name: 'Menu',
  components: { Treeselect },
  data() {
    const columns = [
      {
        title: '菜单名称',
        dataIndex: 'name'
      },
      {
        title: '排序',
        dataIndex: 'treeSort'
      },
      {
        title: '权限标识',
        dataIndex: 'menuWeb'
      },
      {
        title: '组件路径',
        dataIndex: 'componentPath'
      },
      {
        title: '显示状态',
        dataIndex: 'isShow',
        scopedSlots: { customRender: 'isShow' }
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        customRender(createDate) {
          return parseTime(createDate)
        }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        scopedSlots: { customRender: 'operate' }
      }
    ]

    return {
      // pcode字典
      yesNoDict: [],
      viewTypeDict: [],
      menuTypeDict: [],
      requestTypeDict: [],

      queryParams: {
        name: undefined,
        isShow: undefined
      },

      tableParams: {
        columns,
        loadData: parameter => {
          console.log((this))
          const requestParameters = Object.assign({}, parameter, this.$parseQueryParams(this.queryParams))
          return getMenuTreeApi(requestParameters)
            .then(res => {
              return deleteNullChildren(res.data)
            })
        },
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange
        },
        selectedRowKeys: [],
        selectedRows: [],
        initRequest: true
      },

      title: '',
      open: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      menuForm: {},
      menuFormRules: {
        parentId: [
          { required: true, message: '上级菜单不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        treeSort: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ]
      },

      menuTree: [],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  created() {
    this.initDict()
    // this.getTableDataByFirst()
  },
  methods: {
    getTableDataByFirst() {
      this.$refs.table && this.$refs.table.refresh(true)
    },

    /**
     * 初始化数据字典
     */
    initDict() {
      this.$getCodeDictMap(this, {
        MENU_TYPE: 'menuTypeDict',
        VIEW_TYPE: 'viewTypeDict',
        YES_NO: 'yesNoDict',
        REQUEST_TYPE: 'requestTypeDict'
      })
    },
    /**
     * 重置菜单表单
     */
    resetMenuForm() {
      this.menuForm = {
        id: undefined, // 菜单ID
        name: undefined, // 菜单名称
        parentId: undefined, // 上级ID
        treeSort: 0, // 排序
        menuIcon: undefined, // 图标
        menuUrl: undefined, // 路由地址
        componentPath: undefined, // 组件路径
        menuType: 'DIRECTORY', // 菜单类型（M目录 C菜单 F按钮）
        isShow: 'SHOW',
        menuWeb: undefined,
        menuHref: undefined,
        method: undefined,
        redirect: undefined,
        keepAlive: 'YES'
      }
    },

    onOpenAddMenuModal(index, row) {
      this.resetMenuForm()
      this.onGetTreeMenu()
      // if (row) {
      //   this.menuForm.parentId = row.menu_id
      // }
      this.title = '新建菜单'
      this.open = true
    },

    /**
     * 打开修改部门弹窗
     * @param index 当前索引
     * @param row 当前部门数据
     */
    onOpenModifyMenuModal(index, menu) {
      this.resetMenuForm()
      this.onGetTreeMenu()
      this.menuForm = {
        ...menu
      }
      this.title = '修改菜单'
      this.open = true
    },

    /**
     * 获取菜单列表
     */
    onGetTableData: debounce(function() {
      this.loading = true
      const params = {
        ...this.$parseQueryParams(this.queryParams)
      }
      getMenuTreeApi(params).then((res) => {
        this.loading = false
        if (res && res.code === 'A00000') {
          this.tableData = res.data
        }
      }).catch(() => {
        this.loading = false
      })
    }),

    /**
     * 新增或修改菜单
     */
    onAddOrModifyMenu: debounce(function() {
      this.$refs.menuForm.validate((valid) => {
        if (valid) {
          const params = {
            id: this.menuForm.id, // 菜单ID
            name: this.menuForm.name, // 菜单名称
            parentId: this.menuForm.parentId, // 上级ID
            treeSort: this.menuForm.treeSort, // 排序
            menuUrl: this.menuForm.menuUrl, // 路由地址
            componentPath: this.menuForm.componentPath, // 组件路径
            menuType: this.menuForm.menuType, // 菜单类型（M目录 C菜单 F按钮）
            isShow: this.menuForm.menuType === 'BUTTON' ? 'HIDDEN' : this.menuForm.isShow,
            menuWeb: this.menuForm.menuWeb,
            menuHref: this.menuForm.menuHref,
            menuIcon: this.menuForm.menuIcon,
            method: this.menuForm.method,
            keepAlive: this.menuForm.keepAlive,
            redirect: this.menuForm.redirect
          }
          // 新增菜单
          if (this.menuForm.id === undefined) {
            addMenuApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            // 修改菜单
            modifyMenuApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    }),

    /**
     * 删除菜单
     */
    onDeleteMenu(index, menu) {
      this.$confirm({
        title: '提示',
        content: '确认删除当前菜单, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          const params = {
            id: menu.id
          }
          deleteMenuApi(params).then((res) => {
            if (res && res.code === 'A00000') {
              this.$message.success(res.msg)
              this.getTableDataByFirst()
            }
          })
        }
      })
    },

    onGetTreeMenu() {
      getMenuTreeApi().then((res) => {
        if (res && res.code === 'A00000') {
          this.menuTree = [
            {
              id: '1000000000000000000',
              name: '主菜单',
              children: this.$deleteNullChildren(res.data)
            }
          ]
          // this.menuTree = res.data
        }
      })
    },

    /**
     * 表格多选示例
     * @param selectedRowKeys
     * @param selectedRows
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.tableParams.rowSelection.selectedRowKeys = selectedRowKeys

      // this.tableParams.selectedRowKeys = selectedRowKeys
      // this.tableParams.selectedRows = selectedRows
    }
  }
}
</script>

<style scoped>
/** 全局表格头部操作 */
.table_title_operate{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

</style>
